import { Directive, HostListener, Input } from '@angular/core';
import { FormControl, NG_VALIDATORS, Validator } from '@angular/forms';

@Directive({
  selector: '[oyRInputLength]',
  providers: [{ provide: NG_VALIDATORS, useExisting: RInputLengthDirective, multi: true }]
})

/**
 * 描述：Input长度校验控制
 * 公司：xxx有限公司
 * 版权：xxx2020
 * 作者：oyjl
 * 时间：2020-03-27 09:23:31
 */
export class RInputLengthDirective implements Validator {

  @Input() oyRInputLength: Array<number>;

  @HostListener('input', ['$event'])
  validate(c: any) {
    if (c instanceof FormControl) {
      const length = (c.value && c.value.length) || 0;
      if (length < this.oyRInputLength[0] || length > this.oyRInputLength[1]) {
        return c;
      } else {
        return null;
      }
    } else {
      const fElement = c.target.parentNode.querySelector('.length-tips');
      if (fElement) {
        fElement.remove();
      }
      const length = c.target.value.length;
      if (length < this.oyRInputLength[0] || length > this.oyRInputLength[1]) {
        const element = document.createElement('p');
        element.setAttribute('style', 'color:red;margin:0;text-align: left');
        element.setAttribute('class', 'length-tips');
        element.textContent = '字段长度范围为：' + this.oyRInputLength.join('-');
        c.target.parentNode.appendChild(element);
      }
    }
  }
}
